import { reactive, computed, toRefs, onMounted } from "vue";
import request from "@/utils/request";

/**
 * 加载更多列表
 * @returns
 */
export function useInfiniteList({
  url,
  params,
  requestType='get',
  initialData = [],
  initialPage = 1,
  initialPageSize = 20,
  initialPages = 0,
}) {
  const state = reactive({
    conditions: {},
    list: initialData,
    current: initialPage,
    size: initialPageSize,
    pages: initialPages,
    loading: false,
    error: null,
  });

  const hasMore = computed(() => state.pages > state.current);

  const fetch = async (conditions = {}, append = false) => {
    state.conditions = conditions;
    state.loading = true;
    state.error = null;
    return request[requestType](url, {
			...conditions,
			current: state.current,
			size: state.size
		}).then((res) => {
        const { data = {} } = res;
        const { records = [], pages } = data;
        if (append) {
          state.list = [...state.list, ...records];
        } else {
          state.list = records;
        }
        state.pages = pages;
      })
      .catch((err) => {
        state.error = err;
      })
      .finally(() => {
        state.loading = false;
      });
  };

  const search = (conditions) => {
    state.current = 1;
    fetch(conditions);
  };

  const loadMore = (done) => {
    state.current += 1;
    fetch(state.conditions, true).then(() => done());
  };

  const reset = () => {
    state.conditions = {};
    state.list = initialData;
    state.current = initialPage;
    state.size = initialPageSize;
    state.pages = initialPages;
    state.loading = false;
    state.error = null;
  };

  onMounted(() => fetch(params));

  return {
    ...toRefs(state),
    hasMore,
    search,
    loadMore,
    reset
  };
}
